<?php

class CheltuialaForm extends BaseCheltuialaForm
{
    // folosesc denumiri simbolice pentru campurile din formular
    // acestea trebuie sa corespunda cu denumirile coloanelor din tabela `cheltuiala`
    // ATENTIE: unele valoari sunt folosite si in scriptul cheltuieli.js
    const FURNIZOR      = 'furnizor';
    const DATA_EMITERII = 'data_emiterii';
    const SCADENTA      = 'scadenta';
    const DESCRIERE     = 'descriere';
    const SERIE         = 'serie';
    const VALOARE       = 'valoare';
    const COLOANA       = 'coloana_id';
    const TARGET        = 'target_id';
    const TIP           = 'tip_cheltuiala_id';

    // alte coloane din tabela `cheltuiala`, care sunt populate automat si nu sunt afisate in formular
    const USER_ID   = App::USER_ID;
    const LUNA      = App::LUNA;

    public function configure()
    {
        // (re)definire campuri
        $this->configureWidgets();

        // (re)definire validatori
        $this->configureValidators();
    }

    /**
     *
     * @param array $translationTable Maps the column ID to the corresponding criterion ID
     * @return type
     */
    public function getCriteriuForms(&$translationTable = array())
    {
        $forms = array();

        // extrag id-urile coloanelor dispobibile
        $coloanaValues = $this->getWidget(self::COLOANA)->getChoices();

        foreach ($coloanaValues as $coloanaId => $coloanaName)
        {
            if (!$coloanaId) continue;

            $coloanaObject = ColoanaPeer::find($coloanaId);
            $criteriuId = $coloanaObject->getCriteriuId();

            $translationTable[$coloanaId] = $criteriuId;

            if ($coloanaObject && empty($forms[$criteriuId]))
            {
                $form = $coloanaObject->getCriteriuForm();
                if ($form)
                {
                    $form->setWrapperName($this->getFormName());
                    $forms[$criteriuId] = $form;
                }
            }
        }

        return $forms;
    }


    protected function getColoanaCriteria()
    {
        $criteria = new Criteria();
        $criteria
            ->addOr(ColoanaPeer::USER_ID, null, Criteria::ISNULL)
            ->addOr(ColoanaPeer::USER_ID, 0)
            ->addOr(ColoanaPeer::USER_ID, UserCriteria::getUserId());

        return $criteria;
    }

    /**
     * (Re)definire campuri
     */
    protected function configureWidgets()
    {
        // se folosesc doar anumite campuri din tabela `cheltuiala` care sa fie afisate in formular
        $this->useFields(array(self::TIP, self::SERIE, self::FURNIZOR, self::DESCRIERE, self::DATA_EMITERII, self::SCADENTA, self::VALOARE, self::COLOANA, self::TARGET));

        $this->setWidget(self::DESCRIERE, new sfWidgetFormTextarea());

        $this->setWidget(self::DATA_EMITERII, new sfWidgetFormInputText());
        $this->setWidget(self::SCADENTA, new sfWidgetFormInputText());

        $this->getWidget(self::COLOANA)
            ->setOption('criteria', $this->getColoanaCriteria())
            ->setOption('add_empty', 'Selectaţi coloana')
            ->setAttribute('data-request-url', sfContext::getInstance()->getController()->genUrl('cheltuieli/xCriteriuForm'));

        // redefinesc label-urile
        $this->setLabels(array(
            self::SERIE   => 'Serie/Număr',
            self::DATA_EMITERII => 'Data emiterii',
            self::COLOANA       => 'Coloana din lista de plată',
        ));

        // definesc valorile initiale
        $this->setDefaults(array(
            self::DATA_EMITERII => date('d-m-Y'),
        ));

        // campul TARGET este populat automat in interfata in momentul salvarii cheltuielii (nu se completeaza manual)
        $this->setWidget(self::TARGET, new sfWidgetFormInputHidden());
    }

    /**
     * (Re)definire validatori
     */
    protected function configureValidators()
    {
        $this->getValidator(self::COLOANA)
                ->setOption('criteria', $this->getColoanaCriteria());

        $this->setValidator(self::TARGET, new TargetValidator());

    }

    protected function hasExtraForm()
    {
        return isset($this->embeddedForms[CriteriuForm::NAME]);
    }

    protected function saveExtraForm()
    {
        if (!$this->hasExtraForm()) return;

        $values = $this->getValues();
        $this->getEmbeddedForm(CriteriuForm::NAME)->save($values[CriteriuForm::NAME], $this->getObject()->getId());

    }

    /**
     * Aici se adauga alte sub-formulare
     *
     * @param array $values
     */
    protected function _prepareFormSchema( $values )
    {
        // verific daca formularul cuprinde informatii suplimentare (verificarea se face in functie de coloana aleasa)
        $coloana_id = $values[self::COLOANA];
        $coloana = ColoanaPeer::find($coloana_id);
        if ($coloana)
        {
            $criteriuForm = $coloana->getCriteriuForm();
            if ($criteriuForm)
            {
                $this->embedForm( $criteriuForm );

                // adaug post-validatorul pt formularul suplimentar
                $criteriuPostValidator = $criteriuForm->getPostValidator();
                $this->mergePostValidator($criteriuPostValidator);
            }
        }

    }

    /**
     * Functia se rescrie pentru ca TARGET_ID trebuie calculat pe baza listei de apartamente
     *
     * @param array $values
     */
    protected function _updateObject( $values )
    {
        $values[self::TARGET]   = TargetApartamentPeer::getTargetId($values[self::TARGET], true);
        $values[self::USER_ID]  = UserCriteria::getUserId();
        $values[self::LUNA]     = App::getWorkingMonth();

        return $values;
    }

    protected function _afterSave()
    {
        // salveaza parametrii suplimentari
        $this->saveExtraForm();
    }

}
